package com.carrie.controller;

import com.alibaba.fastjson2.JSON;
import com.carrie.config.security.JwtUtils;
import com.carrie.model.entity.UserDetails;
import com.carrie.service.impl.UserServiceImpl;
import com.carrie.tools.LogUtils;
import com.carrie.tools.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.*;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * @author XuHaiLong
 * @since 2025/4/15 11:29
 */
@RestController
public class LoginController {
    private final AuthenticationManager authenticationManager;

    public LoginController(AuthenticationManager authenticationManager) {
        this.authenticationManager = authenticationManager;
    }
    @Autowired
    UserServiceImpl userService;

    @PostMapping("/authenticate")
    public ResponseEntity<Result> authenticate(@RequestBody Map<String, String> loginData) {
        String username = loginData.get("username");
        String password = loginData.get("password");

        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(username, password);
        try {
            Authentication authentication = authenticationManager.authenticate(authenticationToken);
            SecurityContextHolder.getContext().setAuthentication(authentication);
            // 获取当前认证信息
            Authentication currentAuthentication = SecurityContextHolder.getContext().getAuthentication();
            // 获取主要信息
            Object principal = currentAuthentication.getPrincipal();
            String key = JwtUtils.generateToken(currentAuthentication.getName());
            UserDetails res = userService.getUserDetailsByLogin(username);
            HashMap<String, Object> map = new HashMap<>();
            map.put("jwtToken", key);
            map.put("data", res);
            LogUtils.info(JSON.toJSONString(principal));
            return new ResponseEntity<>(new Result(200, "登录成功", map), HttpStatus.OK);
        } catch (BadCredentialsException e) {
            LogUtils.info(e.getMessage());
            return new ResponseEntity<>(new Result(1001, e.getMessage()), HttpStatus.UNAUTHORIZED);
        } catch (DisabledException e) {
            return new ResponseEntity<>(new Result(1003, "用户已被禁用"), HttpStatus.FORBIDDEN);
        } catch (LockedException e) {
            return new ResponseEntity<>(new Result(1003, "用户已被锁定"), HttpStatus.FORBIDDEN);
        } catch (Exception e) {
            return new ResponseEntity<>(new Result(500, "登录时发生未知错误: " + e.getMessage()), HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
}